//
//  UIImage+MBExtension.m
//  LiveBroadcast
//
//  Created by Maybe on 2019/5/1.
//  Copyright © 2019 moonBroadcast. All rights reserved.
//

#import "UIImage+MBExtension.h"
#import <Photos/Photos.h>

@implementation UIImage (MBExtension)
//压缩图片到多少 KB 以下
//先压缩图片质量，如果已经小于指定大小，就可得到清晰的图片，否则再压缩图片尺寸
+ (UIImage *)compressImage:(UIImage *)image toKBByte:(NSUInteger)KBvalue {
    
    NSUInteger maxLength = KBvalue * 1024;
    CGFloat compression = 1;
    NSData *data        = UIImageJPEGRepresentation( image, compression );
    if ( data.length < maxLength ) return image;
    CGFloat max = 1;
    CGFloat min = 0;
    for ( int i = 0; i < 6; ++i ) {
        compression = ( max + min ) / 2;
        data        = UIImageJPEGRepresentation( image, compression );
        if ( data.length < maxLength * 0.9 ) {
            min = compression;
        } else if ( data.length > maxLength ) {
            max = compression;
        } else {
            break;
        }
    }
    UIImage *resultImage = [UIImage imageWithData:data];
    if ( data.length < maxLength ) {
       
        return resultImage;
    }
    // Compress by size
    NSUInteger lastDataLength = 0;
    while ( data.length > maxLength && data.length != lastDataLength ) {
        lastDataLength = data.length;
        CGFloat ratio  = (CGFloat) maxLength / data.length;
        CGSize  size   = CGSizeMake(
                                    ( NSUInteger )( resultImage.size.width * sqrtf( ratio ) ),
                                    ( NSUInteger )(
                                                   resultImage.size.height *
                                                   sqrtf( ratio ) ) ); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext( size );
        [resultImage drawInRect:CGRectMake( 0, 0, size.width, size.height )];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation( resultImage, compression );
    }
    return resultImage;
}
/*多张图片上下拼接*/
+ (UIImage *)combineImage:(NSArray<UIImage *> *)images{
    UIImage *resultImage = [[UIImage alloc]init];
    if (images.count < 2) {
        return resultImage;
    }
    UIImage *tmpImage = nil;
    for (NSInteger i = 0; i < images.count -1; i++) {
        if (tmpImage == nil) {
           tmpImage = [UIImage combineImageUpImage:images[i] DownImage:images[i+1]];
        }else {
           tmpImage = [UIImage combineImageUpImage:tmpImage DownImage:images[i+1]];
        }
    }
    resultImage = tmpImage;
    return resultImage;
}

/*2张图片上下拼接*/
+ (UIImage *)combineImageUpImage:(UIImage *)upImage  DownImage:(UIImage *)downImage{
    
    UIImage * image1 = upImage;
    UIImage * image2 = downImage;
    
    if (image1 == nil) {
        return image2;
    }
    CGFloat width = image1.size.width;
    CGFloat height = image1.size.height  + image2.size.height;
    CGSize offScreenSize = CGSizeMake(width, height);
    // UIGraphicsBeginImageContext(offScreenSize);用这个重绘图片会模糊
    UIGraphicsBeginImageContextWithOptions(offScreenSize, NO, [UIScreen mainScreen].scale);
    
    CGRect rectUp = CGRectMake(0, 0, image1.size.width, image1.size.height);
    [image1 drawInRect:rectUp];
    
//    CGRect rectDown = CGRectMake((width - image2.size.width)/2, rectUp.origin.y + rectUp.size.height, image2.size.width, image2.size.height);
    CGFloat imageX = (width - image2.size.width) > 0 ? (width - image2.size.width)/2 : 0;
    
    CGRect rectDown = CGRectMake(imageX, rectUp.origin.y + rectUp.size.height, image2.size.width, image2.size.height);

    [image2 drawInRect:rectDown];
    
    UIImage* imagez = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imagez;
}

/*保存图片在相册 并获取图片*/
+(void)savePhotoalbumWithImage:(UIImage *)image complete:(void (^)(NSData* imageData))successBlock{
    NSMutableArray *imageIDs = [NSMutableArray array];
    [[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{
       PHAssetChangeRequest *req =    [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        [imageIDs addObject:req.placeholderForCreatedAsset.localIdentifier];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            __block PHAsset *imageAsset = nil;
            PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:imageIDs options:nil];
            [result enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                imageAsset = obj;
                *stop = stop;
            }];
            if (imageAsset) {
                [[PHImageManager defaultManager] requestImageDataForAsset:imageAsset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
//                    NSLog(@"imageData = %@", imageData);
//                     UIImage *image = [UIImage imageWithData: imageData];

                    successBlock(imageData);
                }];
            }
        }
        
    }];
}

/*获取 相册视频路径以及文件*/
+(void)gainPhotoalbumVideo:(PHAsset *)videoAsset complete:(void(^)(NSString *videoPath,NSData *videoData))successBlock {
    if (videoAsset.mediaType == PHAssetMediaTypeVideo) {
        PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc]init];
        options.version = PHImageRequestOptionsVersionCurrent;
        options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
        [[PHImageManager defaultManager]requestAVAssetForVideo:videoAsset options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            AVURLAsset *urlAsset = (AVURLAsset *)asset;
            NSURL *url = urlAsset.URL;
            NSString *videoPath = [url absoluteString];
            NSData *data = [NSData dataWithContentsOfURL:url];
            successBlock(videoPath,data);
        }];
    }
}

@end
